"use client";
import { Button, Col, Form, Input, Row, Table, Modal, Switch, Select, Space, App } from "antd";
import type { FormInstance } from 'antd';
import { Pagination } from "@/utils/db/dbTools";
import React, { useEffect, useState, useRef } from "react";
import { sysDictTableColumns } from "./tools";
import { system } from "@/forent-api/api";
import TextArea from "antd/es/input/TextArea";

const { Option } = Select;

const SystemDictContent: React.FC = () => {
    const [pagination, setPagination] = useState<Pagination>({
        current: 1,
        pageSize: 10,
        total: 0,
    });
    const { message, modal } = App.useApp();

    const [isModalVisible, setIsModalVisible] = useState(false);
    const [dictModelTitle, setDictModelTitle] = useState("添加字典");
    const [form] = Form.useForm();
    const searchFormRef = useRef<FormInstance>(null);
    const [dictTableData, setDictTableData] = useState([]);
    const [dictTypes, setDictTypes] = useState<string[]>([]);

    const fetchDictTypes = async () => {
        try {
            const res = await system.getDictTypeList();
            if (res.data) {
                setDictTypes(res.data);
            }
        } catch (error) {
            message.error("获取字典类型失败");
        }
    };

    const getDictListAction = (searchParams = {}) => {
        const params = {
            page: pagination.current,
            pageSize: pagination.pageSize,
            ...searchParams
        };
        system.getDictList(params).then((res) => {
            if(res.data){
                setDictTableData(res.data.data);
                setPagination({
                    ...pagination,
                    current: res.data.page,
                    total: res.data.total as number,
                });
            }
        });
    };

    const handleSearch = (values: any) => {
        setPagination(prev => ({ ...prev, current: 1 }));
        getDictListAction(values);
    };
    
    const handleOk = async () => {
        const data = await form.validateFields();
        data.del_flag = data.del_flag ? 1 : 0;
        if (form.getFieldValue("action") == "add") {
            await system.addDict(data);
            setIsModalVisible(false);
            form.resetFields();
            getDictListAction();
        } else {
            data.id = form.getFieldValue("key");
            await system.updateDict(data);
            setIsModalVisible(false);
            form.resetFields();
            getDictListAction();
        }
    };

    const handleCancel = () => {
        form.resetFields();
        setIsModalVisible(false);
    };

    useEffect(() => {
        getDictListAction();
        fetchDictTypes();
    }, [pagination.current, pagination.pageSize]);

    const handleTableChange = (pagination: any) => {
        setPagination(prev => ({ ...prev, current: pagination.current }));
    };

    const addDict = () => {
        setDictModelTitle("添加字典");
        showDictModal("add");
    };

    const showDictModal = (action: string) => {
        form?.setFieldsValue({ action, del_flag: true });
        setIsModalVisible(true);
    };

    const onEditDict = (action: string, record: any) => {
        setDictModelTitle("编辑字典");
        showDictModal(action);
        form?.setFieldsValue({
            ...record,
            del_flag: record.del_flag === 1,
        });
    };

    const onDeleteDict = async (record: any) => {
        modal.confirm({
            title: "确认删除",
            content: "确定要删除该字典吗？",
            onOk: async () => {
                await system.deleteDict({ id: record.id });
                getDictListAction();
            },
        });
    };

    return (
        <div className="h-full flex flex-col bg-white p-4 rounded-lg">
            <Form
                layout="inline"
                ref={searchFormRef}
                onFinish={handleSearch}
                className="mb-4"
            >
                <Form.Item label="字典名称" name="dict_name">
                    <Input placeholder="请输入字典名称" allowClear />
                </Form.Item>
                <Form.Item label="字典类型" name="dict_type">
                    <Select placeholder="请选择字典类型" style={{ width: 150 }} allowClear>
                        {dictTypes.map(type => (
                            <Option key={type} value={type}>{type}</Option>
                        ))}
                    </Select>
                </Form.Item>
                <Form.Item>
                    <Space>
                        <Button type="primary" htmlType="submit">查询</Button>
                        <Button onClick={() => {
                            searchFormRef.current?.resetFields();
                            handleSearch({});
                        }}>重置</Button>
                        <Button type="primary" ghost onClick={addDict}>新增</Button>
                    </Space>
                </Form.Item>
            </Form>
            <Table
                columns={sysDictTableColumns(onEditDict, onDeleteDict)}
                dataSource={dictTableData}
                pagination={{ ...pagination, position: ["bottomCenter"] }}
                onChange={handleTableChange}
                scroll={{ y: "calc(100vh - 320px)" }}
            />
            <Modal
                title={dictModelTitle}
                open={isModalVisible}
                onOk={handleOk}
                onCancel={handleCancel}
                width={600}
            >
                <Form form={form} layout="vertical">
                    <Form.Item name="action" hidden><Input /></Form.Item>
                    <Form.Item name="key" hidden><Input /></Form.Item>
                    <Row gutter={16}>
                        <Col span={12}>
                            <Form.Item name="dict_name" label="字典名称" rules={[{ required: true }]}>
                                <Input />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item name="dict_type" label="字典类型" rules={[{ required: true }]}>
                                <Input />
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row gutter={16}>
                        <Col span={12}>
                            <Form.Item name="dict_id" label="字典ID" rules={[{ required: true }]}>
                                <Input />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item name="del_flag" label="状态" valuePropName="checked" initialValue={true}>
                                <Switch checkedChildren="启用" unCheckedChildren="禁用" />
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row gutter={16}>
                        <Col span={24}>
                            <Form.Item name="other" label="补充">
                                <Input />
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row gutter={16}>
                        <Col span={24}>
                            <Form.Item name="description" label="描述">
                                <TextArea />
                            </Form.Item>
                        </Col>
                    </Row>
                </Form>
            </Modal>
        </div>
    );
};

export default function SystemDict() {
    return (
        <div className="h-full rounded-lg px-2">
            <App>
                <SystemDictContent />
            </App>
        </div>
    );
}
